/**
 * 分类的编辑弹框，通过判断props是否传入data，决定是新增还是编辑物资分类
 */

import { addCategory, updateCategory } from '@/services/categoryApi';
import { getCategoryList } from '@/services/categoryLocationApi';
import {
  ModalForm,
  ProFormDigit,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import { message } from 'antd';
import { useEffect, useRef } from 'react';

interface Props {
  open: boolean;
  data?: CATEGORY.CategoryModel | null;
  onFinish: () => void;
}

export default function CategoryEditDrawer(props: Props) {
  const formRef = useRef<ProFormInstance>();

  useEffect(() => {
    if (props.open && props.data) {
      formRef.current?.setFieldsValue({
        ...props.data,
        parentId: props.data.parentId || undefined, // 传空字符串时，需要转成 undefined 才能显示 placeholder
      });
    }
  }, [props.data, props.open]);

  const requestAdd = useRequest(addCategory, {
    manual: true,
    onSuccess() {
      message.success('新增成功');
      props.onFinish();
    },
  });
  const requestUpdate = useRequest(updateCategory, {
    manual: true,
    onSuccess() {
      message.success('更新成功');
      props.onFinish();
    },
  });
  return (
    <ModalForm
      formRef={formRef}
      open={props.open}
      width="20vw"
      title={props.data ? '编辑分类' : '新增分类'}
      drawerProps={{
        destroyOnClose: true,
        onClose: props.onFinish,
      }}
      onOpenChange={(_open) => !_open && props.onFinish()}
      onFinish={async (values: CATEGORY.CategoryModel) => {
        // 点击确定按钮时触发
        const params = { ...values };
        if (props.data) {
          params.id = props.data.id;
          await requestUpdate.run(params);
        } else {
          await requestAdd.run(params);
        }
        return true;
      }}
    >
      <ProFormText
        name="name"
        label="分类名称"
        width="md"
        rules={[{ required: true, message: '请填写分类名称' }]}
      />
      <ProFormSelect
        name="parentId"
        label="上级分类"
        width="md"
        placeholder="不选择则为顶级分类"
        request={async () => {
          try {
            const response = await getCategoryList();
            if (response.code === 200 && response.data) {
              return response.data.map((item: CATEGORY.CategoryModel) => ({
                label: item.name,
                value: item.id,
              }));
            }
            return [];
          } catch (error) {
            console.error('获取分类列表失败', error);
            return [];
          }
        }}
      />
      <ProFormTextArea
        name="description"
        label="分类描述"
        width="md"
        placeholder="请输入分类描述"
      />
      <ProFormDigit
        name="sortOrder"
        label="排序序号"
        width="md"
        min={0}
        fieldProps={{ precision: 0 }}
        tooltip="数字越小排序越靠前"
      />
    </ModalForm>
  );
}